#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity

from models import db, User, Role

# 创建认证蓝图
auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    data = request.get_json()
    
    # 验证请求数据
    if not all(k in data for k in ('username', 'email', 'password')):
        return jsonify({
            'status': 'error',
            'message': '缺少必要的字段: username, email, password'
        }), 400
    
    # 检查用户名和邮箱是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({
            'status': 'error',
            'message': f"用户名 '{data['username']}' 已被使用"
        }), 409
    
    if User.query.filter_by(email=data['email']).first():
        return jsonify({
            'status': 'error',
            'message': f"邮箱 '{data['email']}' 已被注册"
        }), 409
    
    # 获取默认角色（如果存在）
    default_role = Role.query.filter_by(name='user').first()
    roles = [default_role] if default_role else []
    
    # 创建新用户
    user = User(
        username=data['username'],
        email=data['email'],
        password=data['password'],
        roles=roles
    )
    
    # 保存到数据库
    db.session.add(user)
    db.session.commit()
    
    return jsonify({
        'status': 'success',
        'message': '用户注册成功',
        'user': user.to_dict()
    }), 201


@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    data = request.get_json()
    
    # 验证请求数据
    if not all(k in data for k in ('username', 'password')):
        return jsonify({
            'status': 'error',
            'message': '缺少必要的字段: username, password'
        }), 400
    
    # 查找用户
    user = User.query.filter_by(username=data['username']).first()
    if not user or not user.check_password(data['password']):
        return jsonify({
            'status': 'error',
            'message': '用户名或密码错误'
        }), 401
    
    # 检查用户是否激活
    if not user.is_active:
        return jsonify({
            'status': 'error',
            'message': '用户账号已被禁用'
        }), 403
    
    # 创建访问令牌
    access_token = create_access_token(identity=user.username)
    
    return jsonify({
        'status': 'success',
        'message': '登录成功',
        'access_token': access_token,
        'user': user.to_dict()
    }), 200


@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def profile():
    """获取当前用户信息"""
    username = get_jwt_identity()
    user = User.query.filter_by(username=username).first()
    
    if not user:
        return jsonify({
            'status': 'error',
            'message': '用户不存在'
        }), 404
    
    return jsonify({
        'status': 'success',
        'user': user.to_dict()
    }), 200